import { Commit } from 'vuex'
import { getUserResentMessage } from '../../api/message'

type ResentMsgLabel = {
  id: number
  msgId: string
  userId: number
  nickname: string
  avatar: string
  content: string
  isLastRead: boolean
}

interface ResentMessageState {
  resentMessageList: ResentMsgLabel[] | null
  hasNewMessageNotification: boolean
  lastReadCount: number
  activeIndex: string
}

const resentMessageModule = {
  state: (): ResentMessageState => ({
    resentMessageList: null,
    hasNewMessageNotification: false,
    lastReadCount: 0,
    activeIndex: ''
  }),
  mutations: {
    SET_RESENT_MESSAGE_LIST(state: ResentMessageState, resentMsgList: ResentMsgLabel[]) {
      state.resentMessageList = resentMsgList
      state.lastReadCount = 0
      if (resentMsgList) {
        resentMsgList.forEach((item: ResentMsgLabel) => {
          if (item && !item.isLastRead) {
            state.lastReadCount++
          }
        })
        if (state.lastReadCount > 0) {
          state.hasNewMessageNotification = true
        }
      }
    },
    SET_NEW_MESSAGE_NOTIFICATION(state: ResentMessageState, notification: boolean) {
      state.hasNewMessageNotification = notification
    },
    DECREASE_LAST_READ_COUNT(state: ResentMessageState) {
      state.lastReadCount--
    },
    SET_ACTIVE_INDEX(state: ResentMessageState, msgId: string) {
      state.activeIndex = msgId
    }
  },
  actions: {
    async GetResentMessageList({ commit }: { commit: Commit }, args: [userId: number, searchContent: string]) {
      try {
        const res = await getUserResentMessage(args[0], args[1])
        if (res.code === 200) {
          commit('SET_RESENT_MESSAGE_LIST', res.data)
        }
      } catch (err) {
        throw err
      }
    }
  },
  getters: {
    getResentMessageList: (state: ResentMessageState) => state.resentMessageList,
    getNewMessageNotification: (state: ResentMessageState) => state.hasNewMessageNotification,
    getLastReadCount: (state: ResentMessageState) => state.lastReadCount,
    getActiveIndex: (state: ResentMessageState) => state.activeIndex
  }
}

export default resentMessageModule
